package com.gec.system.servcie.impl;

import com.gec.model.system.SysUser;
import com.gec.system.custom.CustomUser;
import com.gec.system.servcie.SysMenuService;
import com.gec.system.servcie.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("username = " + username);
        SysUser sysUser = sysUserService.getUserInfoUserName(username);
        if(null == sysUser) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        if(sysUser.getStatus().intValue() == 0) {
            throw new RuntimeException("账号已停用");
        }

        //通过用户id查询得到该用户所具有的权限集合
        List<String> userPermsList = sysMenuService.findUserPermsList(sysUser.getId());

        //改造成规定的数据类型
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String perms : userPermsList) {
            System.out.println("perms = " + perms);
            authorities.add(new SimpleGrantedAuthority(perms.trim()));
        }
        return new CustomUser(sysUser, authorities);
    }
}